package handler

import (
	"car-trade-mgr/cache"
	"car-trade-mgr/model"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func OrderList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	size, _ := strconv.Atoi(c.DefaultQuery("size", "5"))
	offset := (page - 1) * size

	if size > 50 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "页数<50",
		})
	}

	var order []model.CarOrder

	/*
		SELECT
		cars.id AS CarsID,
		cars.car_name AS CarName,
		cars.car_content AS CarContent,
		cars.car_price AS CarPrice,
		orders.order_name AS OrderName,
		orders.order_content AS OrderContent,
		orders.order_price AS OrderPrice
		FROM
		  cars
		  LEFT JOIN orders ON orders.pid=cars.id
		WHERE
		  orders.id=1
	*/

	redis_key := "order_list_" + strconv.Itoa(page)
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Table("cars").
			Select(
				"orders.id AS OrdersID",
				"cars.car_name AS CarName",
				"cars.car_content AS CarContent",
				"cars.car_price AS CarPrice",
				"orders.order_name AS OrderName",
				"orders.order_content AS OrderContent",
				"orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN orders ON orders.pid=cars.id").
			Debug().
			Offset(offset).
			Limit(size).
			Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &order)
	}

	var total int64
	model.DB.Model(&model.Order{}).Count(&total)

	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  order,
		"total": total,
	})
	return
}

func OrderDetail(c *gin.Context) {
	id := c.Query("id")

	var order []model.CarOrder

	/*
		SELECT
		cars.id AS CarsID,
		cars.car_name AS CarName,
		cars.car_content AS CarContent,
		cars.car_price AS CarPrice,
		orders.order_name AS OrderName,
		orders.order_content AS OrderContent,
		orders.order_price AS OrderPrice
		FROM
		  cars
		  LEFT JOIN orders ON orders.pid=cars.id
		WHERE
		  orders.id=1
	*/

	redis_key := "order_detail_" + id
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	if redisData == "" {
		model.DB.Table("cars").
			Select(
				"orders.id AS OrdersID",
				"cars.car_name AS CarName",
				"cars.car_content AS CarContent",
				"cars.car_price AS CarPrice",
				"orders.order_name AS OrderName",
				"orders.order_content AS OrderContent",
				"orders.order_price AS OrderPrice",
			).
			Joins("LEFT JOIN orders ON orders.pid=cars.id").
			Where("orders.id=?", id).
			Debug().
			Find(&order)
		jsonData, _ := json.Marshal(order)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &order)
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": order,
	})
	return
}
